//
//  SCWeakTimer.m
//  Shuaiche
//
//  Created by dangshuai on 2019/3/21.
//  Copyright © 2019 zzs. All rights reserved.
//

#import "SCWeakTimer.h"

@interface SCWeakTimer ()
@property (nonatomic, copy) timerBlock block;
@property (nonatomic, copy) sustainBlock blockSustain;

@property (nonatomic, assign) NSInteger time;
@property (nonatomic, assign) NSTimeInterval timerStep;
@property (nonatomic, assign) NSTimeInterval pasueTimeStamp;
@end

@implementation SCWeakTimer

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti block:(timerBlock)block {
    SCWeakTimer *wk = [[SCWeakTimer alloc] init];
    wk.block = block;
    return [NSTimer scheduledTimerWithTimeInterval:ti target:wk selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)timerAction {
    !self.block ? : self.block();
}


/*
+ (NSTimer *)sustainedTimerWithTimeInterval:(NSTimeInterval)ti withLive:(NSInteger)time block:(sustainBlock)block {
    SCWeakTimer *wk = [[SCWeakTimer alloc] init];
    wk.blockSustain = block;
    if (time > 0) {
        wk.time = time;
        wk.timerStep = ti;
        [wk observeApplicationActionNotification];
    }
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:ti target:wk selector:@selector(sustainTimerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    return timer;
}

- (void)observeApplicationActionNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
}

- (void)applicationDidBecomeActive {
    NSLog(@"程序激活");
    NSTimeInterval active = [NSDate date].timeIntervalSince1970;
    double aa = active - _pasueTimeStamp;
    NSLog(@"休眠了：%f秒", aa);
//    _time = _time - (active - _pasueTimeStamp);
    if (self.blockSustain) {
        self.blockSustain(_time, _time < 0);
    }
}

- (void)applicationDidEnterBackground {
    _pasueTimeStamp = [NSDate date].timeIntervalSince1970;
    NSLog(@"进入后台");
//    if (self.blockSustain) {
//        self.blockSustain(_time, YES);
//    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)sustainTimerAction {
    _time = _time - _timerStep;
    if (self.blockSustain) {
        self.blockSustain(_time, NO);
    }
}
*/
@end
